package com.nlp.weixin.web.interceptor;

import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.nlp.weixin.web.util.WeiXinUtil;
import com.nlp.weixin.web.wx.WeiXin;
/**
 * 
 * @author zyl
 *
 */
public class AuthInterceptor implements Interceptor{
	private static final Log logger = LogFactory.getLog( AuthInterceptor.class );
	@Override
	public void intercept(ActionInvocation ai) {
		// TODO Auto-generated method stub
		Controller controller = ai.getController();
		HttpServletRequest requst  = controller.getRequest();
		String userId = controller.getCookie("userid", null );
		
		//如果用户id不为空，则用户是再次访问，无需判断
		boolean view = ( userId != null ) ? false : WeiXinUtil.isMicroMessenger(requst);
		if( view ){
			//微信授权
			String from = getFrom(controller);
			String redirect_uri = WeiXin.getHost() + "auth?from=" + URLEncoder.encode(from);
			
			String reqUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
					+ WeiXin.getAppId()
					+ "&redirect_uri=" + URLEncoder.encode(redirect_uri )
					+ "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
			
			controller.redirect(reqUrl);
		}else{
			ai.invoke();
		}
	}
	
	private static String getFrom(Controller controller){
		StringBuffer from = new StringBuffer( controller.getRequest().getRequestURL() );
		
		from.append("?");
		Map<String, String[]> para = controller.getParaMap();
		for (Map.Entry<String, String[]> entry : para.entrySet()) {
			for (String str : entry.getValue() ) {
				if( !str.isEmpty() ){
					from.append( entry.getKey() );
					from.append("=");
					from.append( str );
					from.append("&");
				}
			}
		}
		String source = from.toString();
		if( source.endsWith("&") ){
			source = source.substring(0, source.length() - 1 );
		}
		return source;
	}
}
